package com.jin.lazytool.customevent;

import com.jin.lazytool.entity.EventKeyConvertEntity;
import com.jin.lazytool.entity.IEvent;
import com.jin.lazytool.entity.KeyDownUpEvent;
import com.jin.lazytool.utils.JinUtils;
import javafx.collections.FXCollections;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.GridPane;
import javafx.util.StringConverter;

import java.awt.event.KeyEvent;
import java.util.Collection;

public abstract class CustomKeyDownUpEvent extends CustomEvent {

    private final ChoiceBox<EventKeyConvertEntity> keyCode = new ChoiceBox<>();
    private KeyDownUpEvent event;

    {
        Collection<EventKeyConvertEntity> values = JinUtils.getEventKeyFields().values();
        keyCode.setConverter(new StringConverter<EventKeyConvertEntity>() {
            @Override
            public String toString(EventKeyConvertEntity eventKeyConvertEntity) {
                if (eventKeyConvertEntity == null) return "";
                return eventKeyConvertEntity.getText();
            }

            @Override
            public EventKeyConvertEntity fromString(String s) {
                return JinUtils.getEventKeyFields().get(s);
            }
        });
        keyCode.setItems(FXCollections.observableArrayList(values));
        Tooltip.install(luaButton, new Tooltip("""
                返回对象
                {
                    exeFlag: true, // 是否执行        必须返回
                    time: 0       // 执行前等待时间    必须返回
                }"""));

    }

    @Override
    public void initAddPanel(GridPane grid) {
        grid.addRow(2, new Label("按键"), keyCode);
        grid.addRow(3, new Label("等待时间"), time);
        grid.addRow(4, luaButton, luaScript);
    }

    @Override
    public void initEditPanel(GridPane grid, IEvent event) {
        this.event = (KeyDownUpEvent) event;
        time.setValue(this.event.getTime());
        String keyText = KeyEvent.getKeyText(this.event.getKeyCode());
        keyCode.setValue(JinUtils.getEventKeyFields().get(keyText));
        initAddPanel(grid);
    }

    @Override
    public IEvent fullAddIEvent() {
        event = newEvent();
        event.setKeyCode(keyCode.getValue().getValue());
        event.setTime(time.getNullDefaultValue());
        event.setLua(luaScript.getText());
        return event;
    }

    @Override
    public void fullEditIEvent() {
        event.setKeyCode(keyCode.getValue().getValue());
        event.setTime(time.getNullDefaultValue());
        event.setLua(luaScript.getText());
    }

    abstract KeyDownUpEvent newEvent();

}
